//
//  DwonLoad.m
//  基于NSURLSession的断点下载队列
//
//  Created by 邹浩 on 15/9/17.
//  Copyright (c) 2015年 蓝鸥. All rights reserved.
//

#import "DwonLoad.h"

@interface DwonLoad ()<NSURLSessionDelegate,NSURLSessionDownloadDelegate>
{
    // 用于判断一个任务是否正在下载
    BOOL _isDownLoading;
    
}
@property(nonatomic, strong)VideoModel *model;
// 定义 session
@property(nonatomic, strong)NSURLSession *currentSession;
// 用于可恢复的下载任务的数据
@property(nonatomic, strong)NSData *partialData;
// 可恢复的下载任务
@property(nonatomic, strong)NSURLSessionDownloadTask *task;
@end


@implementation DwonLoad




-(instancetype)initWithDownLoadVideoModel:(VideoModel *)model
{
    
    if (self = [super init]) {
        self.model = model;
    }
    return self;
}

-(void)main
{
    
    NSURLSessionConfiguration *configure = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    self.currentSession = [NSURLSession sessionWithConfiguration:configure delegate:self delegateQueue:nil];
    self.currentSession.sessionDescription = self.model.urlStr;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.model.urlStr]];
    self.task = [self.currentSession downloadTaskWithRequest:request];
    [self.task resume];
    _isDownLoading = YES;
    while (_isDownLoading) {
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]];
    }
    self.partialData = nil;
}
// 暂停
-(void)downLoadPause
{
    NSLog(@"暂停");
    [self.task suspend];
}
// 恢复
-(void)downLoadResume
{
    NSLog(@"恢复下载");
    [self.task resume];
}

#pragma mark delegate(task)
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    
    NSLog(@"path = %@", location.path);
    // 将临时文件剪切或者复制到 caches 文件夹
    NSFileManager *manager = [NSFileManager defaultManager];
    
    NSString *appendPath = [NSString stringWithFormat:@"/%@.mp4",self.model.title];
    NSString *CachesPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) lastObject];
    NSString *file = [CachesPath stringByAppendingString:appendPath];
    
    NSLog(@"%@", file);
    [manager moveItemAtPath:location.path toPath:file error:nil];
    
    _isDownLoading = NO;
    
    // 下载完成发送通知
       
}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    NSLog(@"-----%f", bytesWritten  * 1.0 / totalBytesExpectedToWrite);
    float progressValue = totalBytesWritten / (double)totalBytesExpectedToWrite;
    self.model.progressValue = progressValue;
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.updataBlock) {
            self.updataBlock(self.model);
        }
    });
    
}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{
    NSLog(@"恢复下载的回调");
}



@end
